<template>
	<view class="add-form-container">
		<!-- 顶部导航栏 -->
		<!-- 表单内容区 -->
		<view class="form-content">
			<!-- 基本信息 -->
			<view class="form-card">
				<view class="card-header">
					<text class="card-title">基本信息</text>
				</view>
				
				<view class="form-item">
					<view class="form-label"><text class="required">*</text>采购标题</view>
					<view class="form-value">
						<u-input v-model="dataForm.title" placeholder="请输入采购标题" border="border" clearable maxlength="50" />
					</view>
				</view>
				
				<view class="form-item">
					<view class="form-label">总金额</view>
					<view class="form-value">
						<u-input v-model="dataForm.costAmt" placeholder="总金额" border="border" disabled type="number" />
						<text class="unit-text">元</text>
					</view>
				</view>
				
				<view class="form-item">
					<view class="form-label">备注</view>
					<view class="form-value">
						<u-input v-model="dataForm.summary" placeholder="请输入备注" border="border" type="textarea" />
					</view>
				</view>
			</view>
			
			<!-- 采购物品 -->
			<view class="form-card">
				<view class="card-header">
					<text class="card-title">采购物品</text>
					<u-button type="primary" size="mini" icon="plus" @click="checkProduct">添加物品</u-button>
				</view>
				
				<view class="empty-tip" v-if="dataForm.productList.length === 0">
					<u-empty text="暂无采购物品，请添加" mode="list"></u-empty>
				</view>
				
				<view class="product-list" v-else>
					<view class="product-item" v-for="(item, index) in dataForm.productList" :key="index">
						<view class="product-header">
							<view class="product-title">
								<text class="product-name">{{ item.productName }}</text>
								<text class="product-code">({{ item.productCode }})</text>
							</view>
							<u-icon name="trash" size="40rpx" color="#f56c6c" @click="handleDelList(index)"></u-icon>
						</view>
						
						<view class="product-info">
							<text class="category">{{ item.categoryName }}</text>
							<text class="price">参考价: ¥{{ item.defaultPrice }}</text>
						</view>
						
						<view class="product-edit">
							<view class="edit-item">
								<text class="edit-label">数量</text>
								<u-number-box v-model="item.qty" @change="(value) => watchQty(item)" :min="1"></u-number-box>
								<text class="edit-unit">{{ item.unit || '个' }}</text>
							</view>
							
							<view class="edit-item">
								<text class="edit-label">金额</text>
								<text class="edit-price">{{ item.costJe }}</text>
								<!-- <u-input v-model="item.costJe" placeholder="金额" :disabled="true" type="number" @input="(value) => watchCostAmt(item)" /> -->
								<text class="edit-unit">元</text>
							</view>
						</view>
						
						<view class="product-remark">
							<u-input v-model="item.summary" placeholder="备注信息" border="border" />
						</view>
						
						<u-line></u-line>
					</view>
				</view>
			</view>
			
			<view class="bottom-action">
				<u-button type="primary" @click="dataFormSubmit">提交采购</u-button>
			</view>
		</view>
		
		<!-- 选择物品弹窗 -->
		<u-popup v-model="productChoiceVisible" mode="bottom" border-radius="14" height="85%">
			<view class="product-popup">
				<view class="popup-header">
					<text class="popup-title">选择采购物品</text>
					<u-icon name="close" size="40rpx" @click="closeProductPopup"></u-icon>
				</view>
				
				<!-- <view class="search-box">
					<u-search placeholder="物品编码/物品名称/速记码" v-model="searchParams.keyword" @search="search" @custom="search" :show-action="true" action-text="搜索"></u-search>
				</view> -->
				
				<view class="product-cart-list">
					<scroll-view scroll-y style="height: calc(100% - 120rpx);">
						<view class="empty-tip" v-if="productList.length === 0">
							<u-empty text="暂无物品数据" mode="list"></u-empty>
						</view>
						
						<view class="cart-item" v-for="item in productList" :key="item.productId">
							<view class="cart-item-select">
								<u-checkbox 
									:name="item.productName" 
									v-model="item.checked" 
									shape="circle"
									@change="(value) => handleItemCheck(item, value)"
								></u-checkbox>
							</view>
							<view class="cart-item-info">
								<view class="item-main">
									<view class="item-name">{{ item.productName }}</view>
									<view class="item-code">{{ item.productCode }}</view>
									<view class="item-category">{{ item.categoryName }}</view>
								</view>
								<view class="item-price">
									<text class="price-value">¥{{ item.defaultPrice }}</text>
									<text class="price-unit">/{{ item.unit || '个' }}</text>
								</view>
							</view>
						</view>
						
						<u-loadmore v-if="productList.length > 0" :status="loadStatus" />
					</scroll-view>
				</view>
				
				<view class="cart-footer">
					<view class="cart-footer-left">
						<u-checkbox 
							v-model="isAllSelected" 
							shape="circle"
							@change="handleSelectAll"
						>全选</u-checkbox>
					</view>
					<view class="cart-footer-right">
						<view class="cart-total">
							<text class="cart-total-text">已选：</text>
							<text class="cart-total-count">{{ checkedProducts.length }}</text>
							<text class="cart-total-text">件</text>
						</view>
						<u-button 
							type="primary" 
							@click="chooseProducts" 
							size="normal" 
							:disabled="checkedProducts.length === 0"
						>确认</u-button>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				dataForm: {
					billId: undefined,
					title: '',
					summary: '',
					costAmt: 0,
					productList: []
				},
				productChoiceVisible: false,
				searchParams: {
					keyword: '',
					categoryId: '',
					unitId: ''
				},
				productList: [],
				checkedProducts: [],
				isAllSelected: false,
				selectedMap: {}, // 用于存储已选商品和数量
				categoryOptions: [],
				unitOptions: [],
				page: 1,
				limit: 10,
				total: 0,
				loadStatus: 'loadmore', // 加载状态
				rules: {
					title: [
						{ required: true, message: '请输入采购标题', trigger: ['blur', 'change'] }
					]
				}
			}
		},
		onLoad(options) {
			// 如果是编辑，获取数据
			if(options.billId) {
				this.dataForm.billId = options.billId;
				this.getApplytbillInfo();
			}
			
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			// 获取采购单详情
			getApplytbillInfo() {
				uni.showLoading({
					title: '加载中...'
				});
				
				this.$u.api.applyInfo({
					id: this.dataForm.billId
				}).then(res => {
					this.dataForm = res.data
					
				})
			},
			// 监控数量变化
			watchQty(item) {
				if (!item.costJe) {
					item.costJe = 0;
				}
				if (!item.qty) {
					item.qty = 1;
				}
				item.costJe = parseFloat(item.qty) * parseFloat(item.defaultPrice);
				this.loadCostAmt();
			},
			// 监控金额变化
			watchCostAmt(item) {
				if (!item.costJe) {
					item.costJe = 0;
				}
				this.loadCostAmt();
			},
			// 计算总金额
			loadCostAmt() {
				let costAmt = 0;
				this.dataForm.productList.forEach(item => {
					costAmt += parseFloat(item.costJe || 0);
				});
				this.dataForm.costAmt = costAmt.toFixed(2);
			},
			// 删除采购物品
			handleDelList(index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这个物品吗？',
					success: res => {
						if (res.confirm) {
							this.dataForm.productList.splice(index, 1);
							this.loadCostAmt();
						}
					}
				});
			},
			// 打开选择物品弹窗
			checkProduct() {
				this.productChoiceVisible = true;
				this.searchParams = {
					keyword: '',
					categoryId: '',
					unitId: ''
				};
				
				// 初始化选中状态
				this.selectedMap = {};
				// 将当前已选中的物品加入到selectedMap中
				this.dataForm.productList.forEach(item => {
					this.selectedMap[item.productId] = {
						...item,
						qty: item.qty
					};
				});
				console.log(this.selectedMap)
				
				this.getProductList();
			},
			// 获取物品列表
			getProductList() {
				uni.showLoading({
					title: '加载中...'
				});
				var query = {
					pageNum: this.pageNum,
					pageSize: 10000,
					...this.searchParams
				}
				this.$u.api.productList(query).then(res => {
					console.log(res)
					this.productList = res.data
					
					// 恢复已选状态
					this.productList.forEach(item => {
						if (this.selectedMap[item.productId]) {
							item.checked = true;
						}
					});
					
					this.updateSelectedItems();
					this.loadStatus = this.productList.length >= this.total ? 'nomore' : 'loadmore';
					uni.hideLoading();
				})
			},
			// 处理物品选中状态变化
			handleItemCheck(item, value) {
				if (value) {
					if (!this.isItemSelected(item)) {
						this.selectedMap[item.productId] = {
							...item,
							qty: 1
						};
					}
				} else {
					if (this.selectedMap[item.productId]) {
						delete this.selectedMap[item.productId];
					}
				}
				console.log(this.selectedMap)
				this.updateSelectedItems();
			},
			// 更新所有已选商品
			updateSelectedItems() {
				this.checkedProducts = Object.values(this.selectedMap);
				// 检查是否全选
				this.isAllSelected = this.productList.length > 0 && 
					this.productList.every(item => item.checked);
			},
			// 检查物品是否已被选中
			isItemSelected(item) {
				return !!this.selectedMap[item.productId];
			},
			// 获取已选物品的数量
			getSelectedQty(item) {
				return this.selectedMap[item.productId]?.qty || 0;
			},
			// 更新已选物品的数量
			updateSelectedQty(item, value) {
				if (value > 0) {
					if (this.selectedMap[item.productId]) {
						this.selectedMap[item.productId].qty = value;
					} else {
						item.checked = true;
						this.selectedMap[item.productId] = {
							...item,
							qty: value
						};
					}
				} else {
					item.checked = false;
					delete this.selectedMap[item.productId];
				}
				this.updateSelectedItems();
			},
			// 全选/取消全选
			handleSelectAll(value) {
				this.productList.forEach(item => {
					item.checked = value.value;
					if (value) {
						if (!this.selectedMap[item.productId]) {
							this.selectedMap[item.productId] = {
								...item,
								qty: 1
							};
						}
					} else {
						delete this.selectedMap[item.productId];
					}
				});
				this.updateSelectedItems();
			},
			// 搜索物品
			search() {
				this.page = 1;
				this.getProductList();
			},
			// 确认选择物品
			chooseProducts() {
				if (this.checkedProducts.length === 0) {
					uni.$u.toast('请选择物品');
					return;
				}
				
				// 清空原有列表，使用新选择的列表替换
				this.dataForm.productList = [];
				
				this.checkedProducts.forEach(choiceItem => {
					this.dataForm.productList.push({
						...choiceItem,
						costJe: choiceItem.defaultPrice * choiceItem.qty,
						summary: ''
					});
				});
				
				this.productChoiceVisible = false;
				this.loadCostAmt();
			},
			// 关闭弹窗
			closeProductPopup() {
				this.productChoiceVisible = false;
				this.selectedMap = {};
				this.checkedProducts = [];
				this.isAllSelected = false;
			},
			// 提交表单
			dataFormSubmit() {
				// 表单验证
				if (!this.dataForm.title) {
					uni.$u.toast('请输入采购标题');
					return;
				}
				
				if (this.dataForm.productList.length === 0) {
					uni.$u.toast('请选择采购物品');
					return;
				}
				console.log(this.dataForm)
				uni.showLoading({
					title: '提交中...'
				});
				if(this.dataForm.billId){
					console.log("更新",this.dataForm)
					this.$u.api.updatePurchApply(this.dataForm).then(res => {
						console.log(res)
						uni.hideLoading();
						uni.showToast({
							title: '更新成功',
							icon: 'success',
							duration: 2000,
							success: () => {
								setTimeout(() => {
									uni.$emit('refreshData'); // 发送刷新事件
									uni.navigateBack();
								}, 1500);
							}
						});
					})
				}else{
					console.log("创建",this.dataForm)
					this.$u.api.createPurchApply(this.dataForm).then(res => {
						console.log(res)
						uni.hideLoading();
						uni.showToast({
							title: '提交成功',
							icon: 'success',
							duration: 2000,
							success: () => {
								setTimeout(() => {
									uni.$emit('refreshData'); // 发送刷新事件
									uni.navigateBack();
								}, 1500);
							}
						});
					})
				}
				
			}
		}
	}
</script>

<style lang="scss">
	.add-form-container {
		min-height: 100vh;
		background-color: #f5f6fa;
		display: flex;
		flex-direction: column;
	}
	
	/* 导航栏样式 */
	.navbar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 88rpx;
		background-color: #fff;
		padding: 0 20rpx;
	}
	
	.navbar-left {
		width: 100rpx;
		display: flex;
		align-items: center;
	}
	
	.navbar-title {
		flex: 1;
		text-align: center;
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
	}
	
	.navbar-right {
		width: 100rpx;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}
	
	.form-content {
		flex: 1;
		padding: 20rpx;
		margin-top: 10rpx;
	}
	
	/* 卡片样式 */
	.form-card {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	}
	
	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1px solid #eee;
	}
	
	.card-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}
	
	/* 表单项样式 */
	.form-item {
		margin-bottom: 25rpx;
	}
	
	.form-label {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 10rpx;
		display: flex;
		align-items: center;
	}
	
	.required {
		color: #f56c6c;
		margin-right: 6rpx;
	}
	
	.form-value {
		position: relative;
	}
	
	.unit-text {
		position: absolute;
		right: 20rpx;
		top: 50%;
		transform: translateY(-50%);
		color: #666;
		font-size: 28rpx;
	}
	
	/* 物品列表样式 */
	.empty-tip {
		padding: 30rpx 0;
	}
	
	.product-list {
		padding-top: 10rpx;
	}
	
	.product-item {
		margin-bottom: 30rpx;
	}
	
	.product-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15rpx;
	}
	
	.product-title {
		display: flex;
		align-items: center;
	}
	
	.product-name {
		font-size: 30rpx;
		font-weight: 600;
		color: #333;
	}
	
	.product-code {
		font-size: 24rpx;
		color: #999;
		margin-left: 10rpx;
	}
	
	.product-info {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.category {
		font-size: 24rpx;
		color: #666;
		background-color: #f2f6fc;
		padding: 6rpx 16rpx;
		border-radius: 20rpx;
		margin-right: 15rpx;
	}
	
	.price {
		font-size: 24rpx;
		color: #f56c6c;
	}
	
	.product-edit {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}
	
	.edit-item {
		display: flex;
		align-items: center;
	}
	
	.edit-label {
		font-size: 26rpx;
		color: #666;
		margin-right: 10rpx;
	}
	
	.edit-unit {
		font-size: 26rpx;
		color: #666;
		margin-left: 10rpx;
	}
	
	.product-remark {
		margin-bottom: 20rpx;
	}
	
	/* 购物车样式弹窗 */
	.product-popup {
		display: flex;
		flex-direction: column;
		height: 100%;
		background-color: #fff;
	}
	
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1px solid #eee;
	}
	
	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.search-box {
		padding: 20rpx;
		background-color: #fff;
		border-bottom: 1px solid #f5f5f5;
	}
	
	.filter-box {
		margin-top: 20rpx;
	}
	
	.product-cart-list {
		flex: 1;
		overflow: hidden;
		background-color: #f8f8f8;
	}
	
	.cart-item {
		display: flex;
		align-items: center;
		padding: 30rpx 20rpx;
		border-bottom: 1px solid #f0f0f0;
		background-color: #fff;
	}
	
	.cart-item-select {
		margin-right: 20rpx;
	}
	
	.cart-item-info {
		flex: 1;
		display: flex;
		justify-content: space-between;
	}
	
	.item-main {
		flex: 1;
	}
	
	.item-name {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 8rpx;
	}
	
	.item-code {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 8rpx;
	}
	
	.item-category {
		display: inline-block;
		font-size: 22rpx;
		color: #666;
		background-color: #f2f6fc;
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
	}
	
	.item-price {
		display: flex;
		align-items: baseline;
		margin: 0 30rpx;
	}
	
	.price-value {
		font-size: 28rpx;
		color: #f56c6c;
		font-weight: bold;
	}
	
	.price-unit {
		font-size: 22rpx;
		color: #999;
	}
	
	.cart-item-action {
		width: 180rpx;
		display: flex;
		justify-content: flex-end;
	}
	
	.cart-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-top: 1px solid #eee;
		height: 120rpx;
	}
	
	.cart-footer-left {
		display: flex;
		align-items: center;
	}
	
	.cart-footer-right {
		display: flex;
		align-items: center;
	}
	
	.cart-total {
		margin-right: 30rpx;
	}
	
	.cart-total-text {
		font-size: 26rpx;
		color: #606266;
	}
	
	.cart-total-count {
		font-size: 32rpx;
		color: #f56c6c;
		font-weight: bold;
		margin: 0 4rpx;
	}
	
	.bottom-action {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		background-color: #ffffff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 9;
	
		.price-info {
			font-size: 28rpx;
			color: #606266;
	
			.total-price {
				font-size: 36rpx;
				color: #ff9900;
				font-weight: 600;
			}
		}
	
		.u-button {
			margin-left: 20rpx;
			width: 340rpx;
		}
	}
</style>
